﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web.Hosting;
using NFine.Code;
using NFine.Data;
using NFine.Domain.Entity.Biz;
using NFine.Domain._02_ViewModel;
using NFine.Domain._03_Entity.Biz;
using NFine.Domain._04_IRepository.Biz;
using NFine.Repository.Biz;
using NFine.Domain.IRepository.SystemManage;
using NFine.Repository.SystemManage;

namespace NFine.Application.Biz
{
    public class UserDetailApp
    {
        private IUserDetailRepository userDetailRepository = new UserDetailRepository();
        private IBonusRateRepository bonusRateRepository = new BonusRateRepository();

        private IMemberBonusRepository memberBonusRepository = new MemberBonusRepository();
        private IBalanceRecordRepository balanceRecordRepository = new BalanceRecordRepository();
        private IUserOrderRepository userOrderRepository = new UserOrderRepository();
        private IUserRepository userRepository = new UserRepository();
        private IItemsDetailRepository itemDetailRepository = new ItemsDetailRepository();
        private IUserWithdrawalsRepository userWithDrawalsRepository = new UserWithdrawalsRepository();



        private UserPropertyApp userPropertyApp = new UserPropertyApp();
        private ThreeBonusApp threeBonusApp = new ThreeBonusApp();
        private UserOrderApp userOrderApp = new UserOrderApp();

        private List<BonusRateEntity> listRate = new List<BonusRateEntity>();
        private decimal? minBonusMoney = null;
        private int m_iTreeDepth = -1;
        private DateTime m_dtBonusTime = DateTime.Now;
        private decimal m_dAllBonus = 0.00M;
        private decimal m_dAllManagerBonus = 0.00M;
        private List<UserDetailEntity> m_listAllUserDetail = new List<UserDetailEntity>();

        public int m_iTeamCount = 0;
        public decimal m_dTeamMoney = 0.00M;

        // 代理商分红记录
        private List<MemberBonusEntity> listBonusForMember = new List<MemberBonusEntity>();
        // 代理商资产记录
        private List<UserPropertyEntity> listPropertyForMember = new List<UserPropertyEntity>();
        // 经理分红记录
        private List<MemberBonusEntity> managerBonusList = new List<MemberBonusEntity>();
        // 经理资产记录
        private List<UserPropertyEntity> managerPropertyList = new List<UserPropertyEntity>();



        private Log logger = LogFactory.GetLogger("UserDetailApp");
        #region **************************结算相关****************************

        public int BalanceForMonthNew(DateTime date)
        {
            // *******1.结算相关变量获取********
            // 获取最大树深度
            m_iTreeDepth = getMaxTreeDepth();
            // 获取最小分红额度
            minBonusMoney = bonusRateRepository.GetMinMoney();
            // 获取本月所有代理商消费信息
            var expression = ExtLinq.True<UserDetailEntity>();
            m_listAllUserDetail = userDetailRepository.FindList(expression);

            // *******2.计算所有会员与团队的指定结算月的消费********
            CalculateByMonthNew(date);

            // *******3.代理商分红计算********
            CalculateBonusForMemberNew(date);

            // *******4.经理分红计算********
            CalculateBonusForManagerNew(date);

            // *******5.结算记录插入********
            //decimal allConsume = userDetailRepository.GetAllConsume();
            decimal allConsume = m_listAllUserDetail.Sum(t => t.F_UserConsume).Value;
            BalanceRecordEntity balanceRecordEntity = new BalanceRecordEntity();
            balanceRecordEntity.F_Id = Common.GuId();
            balanceRecordEntity.F_AllConsume = allConsume;
            balanceRecordEntity.F_AllBonus = m_dAllBonus;
            balanceRecordEntity.F_AllManagerBonus = m_dAllManagerBonus;
            balanceRecordEntity.F_BalanceTime = m_dtBonusTime;

            // *******6.相关数据清零********
            // 会员消费清零
            m_listAllUserDetail = m_listAllUserDetail.Select(s => {
                s.F_UserConsume = 0;
                s.F_TeamConsume = 0;
                s.F_TeamBonus = 0;
                return s;
            }).ToList();
            // 订单结算标识
            DateTime CurMonthEnd = DateTime.Parse(date.AddDays(1 - date.Day).AddMonths(1).ToShortDateString()).AddSeconds(-1);
            var expressionOrder = ExtLinq.True<UserOrderEntity>();
            expressionOrder = expressionOrder.And(t => t.F_OrderStatus == 2);
            expressionOrder = expressionOrder.And(t => t.F_OrderTime > date && t.F_OrderTime < CurMonthEnd);
            List<UserOrderEntity> listOrder = userOrderRepository.FindList(expressionOrder);
            listOrder = listOrder.Select(s => {
                s.F_IsBalance = 1;
                return s;
            }).ToList();

            // *******7.启动事务********
            using (var db = new RepositoryBase().BeginTrans())
            {
                // 插入代理商分红记录
                db.Insert(listBonusForMember);

                // 更新代理商资产
                foreach (var memberProperty in listPropertyForMember)
                {
                    db.Update(memberProperty);
                }

                // 插入经理分红记录
                db.Insert(managerBonusList);

                // 更新经理资产
                foreach (var managerProperty in managerPropertyList)
                {
                    db.Update(managerProperty);
                }

                // 结算记录插入
                db.Insert(balanceRecordEntity);



                // 会员数据清零
                foreach (var userDetailEntity in m_listAllUserDetail)
                {
                    db.Update(userDetailEntity);
                }


                // 订单结算标识 
                foreach (var userOrder in listOrder)
                {
                    db.Update(userOrder);
                }
                /*string sql =
                    string.Format(
                        "UPDATE biz_user_order SET F_IsBalance = 1 WHERE F_OrderStatus = 2 AND DATE_FORMAT(F_OrderTime, '%Y%m') = DATE_FORMAT('{0}' , '%Y%m');",
                        date);*/

                return db.Commit();
            }
        }

        /*public bool BalanceForMonth(DateTime date)
        {
            // *******1.结算相关变量获取********
            // 获取最大树深度
            m_iTreeDepth = getMaxTreeDepth();
            // 获取最小分红额度
            minBonusMoney = bonusRateRepository.GetMinMoney();

            // *******1.计算所有会员与团队的指定结算月的消费********
            // 计算指定结算月会员与团队的消费
            CalculateByMonth(date);
            // 获取本月所有代理商消费信息
            var expression = ExtLinq.True<UserDetailEntity>();
            m_listAllUserDetail = userDetailRepository.FindList(expression);

            // *******2.代理商分红计算********
            CalculateBonusForMember(date);

            // *******3.经理分红计算********
            CalculateBonusForManager(date);

            // *******4.结算记录插入********
            decimal allConsume = userDetailRepository.GetAllConsume();
            BalanceRecordEntity balanceRecordEntity = new BalanceRecordEntity();
            balanceRecordEntity.F_Id = Common.GuId();
            balanceRecordEntity.F_AllConsume = allConsume;
            balanceRecordEntity.F_AllBonus = m_dAllBonus;
            balanceRecordEntity.F_AllManagerBonus = m_dAllManagerBonus;
            balanceRecordEntity.F_BalanceTime = m_dtBonusTime;
            balanceRecordRepository.Insert(balanceRecordEntity);

            // *******5.计算后会员消费数据清零********
            if (userDetailRepository.ClearConsumeForBalance() <= 0)
                return false;
            // 订单结算标识  
            userOrderRepository.UpdateBalanceByMonth(date);

            return true;
        }
*/
        public void CalculateByMonthNew(DateTime calculateDate)
        {
            // 清空表会员消费与团队消费
            userDetailRepository.ClearConsumeForBalance();
            // 重新计算会员消费与团队消费
            for (int i = m_iTreeDepth; i >= 0; i--)
            {
                List<UserDetailEntity> list = m_listAllUserDetail.Where(t => t.F_TreeDepth == i).ToList();
                for (int j = 0; j < list.Count; j++)
                {
                    // 自身结算指定月消费计算
                    decimal userConsume =
                        userOrderRepository.SumUserConsumeByMonth(list[j].F_UserId, calculateDate);
                    // 团队月消费
                    decimal teamConsume = userConsume;
                    List<UserDetailEntity> listChild = m_listAllUserDetail.Where(t => t.F_ParentId == list[j].F_UserId).ToList();
                    for (var q = 0; q < listChild.Count; q++)
                    {
                        teamConsume += listChild[q].F_TeamConsume.Value;
                    }

                    m_listAllUserDetail = m_listAllUserDetail.Select(s => {
                        if (s.F_Id == list[j].F_Id)
                        {
                            s.F_UserConsume = userConsume;
                            s.F_TeamConsume = teamConsume;
                        }
                        return s;
                    }).ToList();
                }
            }
        }
        

        public string GetLevelText(UserDetailEntity ud)
        {
            var level = ud.F_UserLevel.ToString();
            if (level.Equals("-3")) {
                return "无效用户";
            }
            var item=itemDetailRepository.FindEntity(t => t.F_ItemId== "dd3f3919-e568-476c-b0d6-7618fa6557eb"&&t.F_ItemCode==level);
            if (item != null)
            {
                return item.F_ItemName;
            }
            else
            {
                return "粉丝";
            }            
        }

        /// <summary>
        /// 分红计算
        /// </summary>
        private bool CaCalculateBonus()
        {
            for (int i = 0; i <= m_iTreeDepth; i++)
            {
                try
                {
                    //开启事务（注意：事务的位置不可变，否则计算不正确）
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        int flag = 0;
                        if (i == 0)
                        {

                        }
                        else
                        {
                            string sql = string.Format("SELECT * from biz_user_detail WHERE F_TeamAllConsume >= {0} and F_TreeDepth = {1}", minBonusMoney, i);
                            List<UserDetailEntity> list = userDetailRepository.FindList(sql);
                          //  list.Find(t => t.F_TeamAllConsume >= minBonusMoney && t.F_TreeDepth == i);
                            for (int j = 0; j < list.Count; j++)
                            {
                                // 团队分红获取
                                decimal money = 0.00M;
                                if (i == 1)
                                {
                                    money =
                                        (list[j].F_TeamConsume.Value * 10000 * GetRateByUserMoney(list[j].F_TeamAllConsume)) / 10000;
                                    list[j].F_TeamBonus = money;
                                    db.Update(list[j]);
                                    ++flag;
                                }
                                else
                                {
                                    money = list[j].F_TeamBonus.Value;
                                }

                                // 自身分红计算
                                string sqlChild = string.Format("SELECT * from biz_user_detail WHERE F_TeamAllConsume >= {0} and F_ParentId = '{1}'", minBonusMoney, list[j].F_UserId);
                                List<UserDetailEntity> listChild = userDetailRepository.FindList(sqlChild);
                                decimal tempMoney = money;
                                for (int m = 0; m < listChild.Count; m++)
                                {
                                    decimal tempChildMoney = (money * 10000 * GetRateByUserMoney(listChild[m].F_TeamAllConsume)) / 10000;
                                    tempMoney -= tempChildMoney;

                                    listChild[m].F_TeamBonus = tempChildMoney;
                                    db.Update(listChild[m]);
                                    ++flag;
                                }
                                // 自身分红记录插入
                                MemberBonusEntity memberBonusEntity = new MemberBonusEntity();
                                memberBonusEntity.F_Id = Common.GuId();
                                memberBonusEntity.F_MemberId = list[j].F_UserId;
                                memberBonusEntity.F_BonusAmount = tempMoney;
                                memberBonusEntity.F_BonusTime = m_dtBonusTime;
                                memberBonusEntity.F_BonusType = 1;
                                memberBonusEntity.F_bz = "平台"+DateTime.Now.Month+"月份的消费补贴";
                                db.Insert(memberBonusEntity);
                                ++flag;

                                // 计算结算分红总额
                                m_dAllBonus += tempMoney;

                                // 更新资产信息
                                userPropertyApp.UpdateMemberProperty(list[j].F_UserId, tempMoney);
                                //TODO 更新平台资产信息
                            }
                            if (flag > 0)
                            {
                                int result = db.Commit();
                                if (result < flag)
                                    return false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            return true;
        }

        
        private void CalculateBonusForMemberNew(DateTime date)
        {
            // 重新初始化
            listBonusForMember = new List<MemberBonusEntity>();
            listPropertyForMember = new List<UserPropertyEntity>();

            // 会员树的深度遍历
            for (int i = 0; i <= m_iTreeDepth; i++)
            {
                if (i > 0)
                {
                    List<UserDetailEntity> list = m_listAllUserDetail.Where(t => t.F_TeamAllConsume >= minBonusMoney && t.F_TreeDepth == i).ToList();
                    for (int j = 0; j < list.Count; j++)
                    {
                        // 团队分红获取
                        decimal money = 0.00M;
                        if (i == 1)
                        {
                            money =
                                (list[j].F_TeamConsume.Value * 10000 * GetRateByUserMoney(list[j].F_TeamAllConsume)) / 10000;
                            list[j].F_TeamBonus = money;

                            m_listAllUserDetail = m_listAllUserDetail.Select(s => {
                                s.F_TeamBonus = s.F_Id == list[j].F_Id ? money : s.F_TeamBonus;
                                return s;
                            }).ToList();
                        }
                        else
                        {
                            money = list[j].F_TeamBonus.Value;
                        }

                        // 自身分红计算
                        List<UserDetailEntity> listChild = m_listAllUserDetail.Where(t => t.F_TeamAllConsume >= minBonusMoney && t.F_ParentId == list[j].F_UserId).ToList();
                        decimal tempMoney = money;
                        for (int m = 0; m < listChild.Count; m++)
                        {
                            // decimal tempChildMoney = (money * 10000 * GetRateByUserMoney(listChild[m].F_TeamAllConsume)) / 10000;
                            ///2018.4.5 傅强修改
                            decimal tempChildMoney = (listChild[m].F_TeamConsume.ToDecimal() * 10000 * GetRateByUserMoney(listChild[m].F_TeamAllConsume)) / 10000;
                            tempMoney -= tempChildMoney;

                            listChild[m].F_TeamBonus = tempChildMoney;
                            
                            m_listAllUserDetail = m_listAllUserDetail.Select(s => {
                                s.F_TeamBonus = s.F_Id == listChild[m].F_Id ? tempChildMoney : s.F_TeamBonus;
                                return s;
                            }).ToList();
                        }
                        // 自身分红记录插入
                        MemberBonusEntity memberBonusEntity = new MemberBonusEntity();
                        memberBonusEntity.F_Id = Common.GuId();
                        memberBonusEntity.F_MemberId = list[j].F_UserId;
                        memberBonusEntity.F_BonusAmount = tempMoney;
                        memberBonusEntity.F_BonusTime = m_dtBonusTime;
                        memberBonusEntity.F_BonusType = 1;
                        memberBonusEntity.F_bz = date.Year + "年" + date.Month + "月份消费补贴";
                        listBonusForMember.Add(memberBonusEntity);

                        // 计算结算分红总额
                        m_dAllBonus += tempMoney;

                        // 更新资产信息
                        listPropertyForMember.Add(userPropertyApp.GetUpdateMemberProperty(list[j].F_UserId, tempMoney));
                    }
                }
            }
        }

        private bool CalculateBonusForMember(DateTime date)
        {
            // 会员树的深度遍历
            for (int i = 0; i <= m_iTreeDepth; i++)
            {
                try
                {
                    //开启事务（注意：事务的位置不可变，否则计算不正确）
                    using (var db = new RepositoryBase().BeginTrans())
                    {
                        int flag = 0;
                        if (i == 0)
                        {

                        }
                        else
                        {
                            List<UserDetailEntity> list = m_listAllUserDetail.Where(t => t.F_TeamAllConsume >= minBonusMoney && t.F_TreeDepth == i).ToList();
                            for (int j = 0; j < list.Count; j++)
                            {
                                // 团队分红获取
                                decimal money = 0.00M;
                                if (i == 1)
                                {
                                    money =
                                        (list[j].F_TeamConsume.Value * 10000 * GetRateByUserMoney(list[j].F_TeamAllConsume)) / 10000;
                                    list[j].F_TeamBonus = money;
                                    // db.Update(list[j]);

                                    m_listAllUserDetail = m_listAllUserDetail.Select(s => {
                                        s.F_TeamBonus = s.F_Id == list[j].F_Id ? money : s.F_TeamBonus;
                                        return s;
                                    }).ToList();

                                    // ++flag;
                                }
                                else
                                {
                                    money = list[j].F_TeamBonus.Value;
                                }

                                // 自身分红计算
                                List<UserDetailEntity> listChild = m_listAllUserDetail.Where(t => t.F_TeamAllConsume >= minBonusMoney && t.F_ParentId == list[j].F_UserId).ToList();
                                decimal tempMoney = money;
                                for (int m = 0; m < listChild.Count; m++)
                                {
                                    decimal tempChildMoney = (money * 10000 * GetRateByUserMoney(listChild[m].F_TeamAllConsume)) / 10000;
                                    tempMoney -= tempChildMoney;

                                    listChild[m].F_TeamBonus = tempChildMoney;
                                    /*db.Update(listChild[m]);
                                    ++flag;*/
                                    m_listAllUserDetail = m_listAllUserDetail.Select(s => {
                                        s.F_TeamBonus = s.F_Id == listChild[m].F_Id ? tempChildMoney : s.F_TeamBonus;
                                        return s;
                                    }).ToList();
                                }
                                // 自身分红记录插入
                                MemberBonusEntity memberBonusEntity = new MemberBonusEntity();
                                memberBonusEntity.F_Id = Common.GuId();
                                memberBonusEntity.F_MemberId = list[j].F_UserId;
                                memberBonusEntity.F_BonusAmount = tempMoney;
                                memberBonusEntity.F_BonusTime = m_dtBonusTime;
                                memberBonusEntity.F_BonusType = 1;
                                memberBonusEntity.F_bz = date.Year+"年"+ date.Month + "月份消费补贴";
                                db.Insert(memberBonusEntity);
                                ++flag;

                                // 计算结算分红总额
                                m_dAllBonus += tempMoney;

                                // 更新资产信息
                                userPropertyApp.UpdateMemberProperty(list[j].F_UserId, tempMoney);
                                

                            }
                            if (flag > 0)
                            {
                                int result = db.Commit();
                                if (result < flag)
                                    return false;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
            return true;
        }

        
        private void CalculateBonusForManagerNew(DateTime date)
        {
            // 初始化记录列表
            managerBonusList = new List<MemberBonusEntity>();
            managerPropertyList = new List<UserPropertyEntity>();

            // 获取本月所有销售额
            decimal allConsume = m_listAllUserDetail.Where(t=>t.F_TreeDepth==1).Sum(t=>t.F_TeamConsume).ToDecimal();  //userDetailRepository.GetAllConsume();

            // 获取经理分红比例
            ThreeBonusEntity threeBonusEntity = threeBonusApp.GetThreeBonus();
            decimal managerRate = threeBonusEntity.F_Manager;

            // 获取所有经理的星数
            int allLevels = userDetailRepository.GetAllLevelCount();
            if (allLevels <= 0)
                return;

            // 获取所有大于等于1星的经理
            var expression = ExtLinq.True<UserDetailEntity>();
            expression = expression.And(a => a.F_ManagerLevel > 0);
            List<UserDetailEntity> list = userDetailRepository.FindList(expression);
            if (list == null || list.Count <= 0)
                return;

            // 分红
            decimal allBonus = allConsume * 10000 * managerRate / 10000;
            m_dAllManagerBonus = allBonus;
            var bamount = (allBonus * 10000 / allLevels) / 10000;
            foreach (var temp in list)
            {
                MemberBonusEntity memberBonusEntity = new MemberBonusEntity();
                memberBonusEntity.F_Id = Common.GuId();
                memberBonusEntity.F_MemberId = temp.F_UserId;
                memberBonusEntity.F_BonusAmount = bamount* temp.F_ManagerLevel;
                memberBonusEntity.F_BonusTime = m_dtBonusTime;
                memberBonusEntity.F_BonusType = 3;
                memberBonusEntity.F_bz = date.Year + "年" + date.Month + "月经理奖励";
                managerBonusList.Add(memberBonusEntity);

                // 更新资产信息
                managerPropertyList.Add(userPropertyApp.GetUpdateMemberProperty(temp.F_UserId, memberBonusEntity.F_BonusAmount.Value));
            }
        }
        
        /// <summary>
        /// 获取当前树最大深度
        /// </summary>
        /// <returns></returns>
        private int getMaxTreeDepth()
        {
            return userDetailRepository.getMaxTreeDepth();
        }

        /// <summary>
        /// 根据深度获取所有记录
        /// </summary>
        /// <param name="treeDepth"></param>
        /// <returns></returns>
        private List<UserDetailEntity> getRecordByTreeDepth(int treeDepth)
        {
            var expression = ExtLinq.True<UserDetailEntity>();
            expression = expression.And(a => a.F_TreeDepth == treeDepth);
            return userDetailRepository.FindList(expression);
        }

        /// <summary>
        /// 根据id获取所有子节点
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        private List<UserDetailEntity> getRecordByParentId(string parentId)
        {
            var expression = ExtLinq.True<UserDetailEntity>();
            expression = expression.And(a => a.F_ParentId == parentId);
            return userDetailRepository.FindList(expression);
        }

        /// <summary>
        /// 获取分红比例
        /// </summary>
        /// <param name="money"></param>
        /// <returns></returns>
        private decimal GetRateByUserMoney(decimal money)
        {
            decimal result = 0.0M;

            if(listRate.Count <= 0)
                listRate = bonusRateRepository.FindList("select * from biz_bonus_rate order by F_Level DESC");

            for (int i = 0; i < listRate.Count; i++)
            {
                if (money >= listRate[i].F_Money)
                {
                    result = listRate[i].F_Rate.Value;
                    break;
                }
            }

            return result;
        }
        /// <summary>
        /// 根据团队消费额得到下一级的升级钱数
        /// </summary>
        /// <param name="money"></param>
        /// <returns></returns>
        private decimal GetMoneyByUserMoney(decimal money)
        {
            decimal result = 0.0M;

            if (listRate.Count <= 0)
                listRate = bonusRateRepository.FindList("select * from biz_bonus_rate order by F_Level DESC");

            var max = 0.0M;
            for (int i = 0; i < listRate.Count; i++)
            {
                if (money >= listRate[i].F_Money)
                {
                    break;
                }
                max = (decimal)listRate[i].F_Money;
            }

            return max;
        }

        #endregion

        public UserDetailEntity GetEntity(string userid)
        {
            return userDetailRepository.FindEntity(t=>t.F_UserId==userid);
        }

        public List<UserDetailEntity> GetConsumeTop()
        {
            var expression = ExtLinq.True<UserDetailEntity>();
            List<UserDetailEntity> list = new List<UserDetailEntity>();
            list = userDetailRepository.FindList("select * from biz_user_detail").OrderByDescending(a=> a.F_UserConsume).Take(10).ToList();
            return list;
        }

        public List<UserCosumeTop> GetConsumeTopNew()// 结算修改标识
        {
            /*var expression = ExtLinq.True<UserOrderEntity>();
            List<UserOrderEntity> list = new List<UserOrderEntity>();*/
            //2018 4 30 傅强 对当前记录统计加入当前月的控制
            string date = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            var db = new RepositoryBase();
            string sql =
                "SELECT F_MemberId, Max(F_Consignee) AS F_Consignee ,SUM(F_TotalMoney) AS F_TotalMoney from biz_user_order where F_OrderStatus>0 and F_BackTime>'"+ date + "' GROUP BY F_MemberId ORDER BY F_TotalMoney DESC limit 10";
            var list = db.FindList<UserCosumeTop>(sql);
            return list;
        }
        /// <summary>
        /// 获取当前月推荐排行
        /// </summary>
        /// <returns></returns>
        public List<UserTuiJianTop> GetTuiJianTop()// 
        {
            /*var expression = ExtLinq.True<UserOrderEntity>();
            List<UserOrderEntity> list = new List<UserOrderEntity>();*/
            //2018 4 30 傅强 对当前记录统计加入当前月的控制
            string date = DateTime.Now.ToString("yyyy-MM-01 00:00:00");
            var db = new RepositoryBase();

            //var list_user=userRepository.FindList(t => t.F_CreatorTime > new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1, 0, 0, 0));
            var list_detail = userDetailRepository.FindList("SELECT b.* FROM `biz_user_detail` b LEFT JOIN `sys_user` a ON a.`F_Id`= b.`F_UserId` WHERE a.`F_CreatorTime`>'"+date+ "' ORDER BY b.`F_ParentId`");
            List<UserTuiJianTop> list_top = new List<UserTuiJianTop>();
            UserTuiJianTop temp = null;
            foreach (var detail in list_detail)
            {
                if (temp == null||temp.F_MemberId!=detail.F_ParentId)
                {
                    temp = new UserTuiJianTop();
                    temp.F_MemberId = detail.F_ParentId;
                    temp.F_Consignee = temp.F_MemberId.Equals("0") ? "平台" : detail.F_ParentName;
                    list_top.Add(temp);
                }
                temp.F_TotalCount += 1;
                if (detail.F_UserLevel > -1)
                    temp.F_Huiyuan += 1;
            }
            return list_top.OrderByDescending(t=>t.F_TotalCount).ToList();
        }
        


        private void GetInfoForMemberDefault(string parentId)
        {
            string sql = string.Format("select * from biz_user_detail where F_ParentId = '{0}' and  F_UserLevel>-1", parentId);
            List<UserDetailEntity> childList = userDetailRepository.FindList(sql);
            m_iTeamCount += childList.Count;
            if (childList.Count > 0)
            {
                foreach (var temp in childList)
                {
                    m_dTeamMoney += userOrderRepository.SumUserConsumeByMonth(temp.F_UserId, DateTime.Now);
                    /*if (temp.F_UserConsume.Value != null)
                        m_dTeamMoney += temp.F_UserConsume.Value;*/
                    GetInfoForMemberDefault(temp.F_UserId);
                }
            }
        }

        public View_MemberDefaultData GetMemberDefaultData(string userId)
        {
            View_MemberDefaultData memberDefaultData = new View_MemberDefaultData();
            if (string.IsNullOrEmpty(userId))
                return memberDefaultData;

            // 获取团队人数以及消费额
            GetInfoForMemberDefault(userId);
            memberDefaultData.teamCount = m_iTeamCount + 1;// 加一是算上自身
            memberDefaultData.teamConsume = m_dTeamMoney;

            // 获取会员本月消费
            memberDefaultData.memberConsume = userOrderRepository.SumUserConsumeByMonth(userId, DateTime.Now);
            memberDefaultData.teamConsume += memberDefaultData.memberConsume;
            var ud = userDetailRepository.FindEntity(t=>t.F_UserId==userId);
            /*if (ud.F_UserConsume != null)
            {
                memberDefaultData.memberConsume = ud.F_UserConsume.Value;
                memberDefaultData.teamConsume += memberDefaultData.memberConsume;// 加上自身消费
            }*/

            memberDefaultData.level = ud.F_UserLevel;
            memberDefaultData.levelA = ud.F_ManagerLevel;
            if(memberDefaultData.levelA==-1)
            { 
                memberDefaultData.memberLast = GetMoneyByUserMoney(ud.F_TeamAllConsume) - ud.F_TeamAllConsume;
            }


            // 获取会员本月分红额
            decimal? userBonus = 0.00M;
            userBonus = memberBonusRepository.GetMemberCurMonthBonus(userId);
            if (userBonus != null)
                memberDefaultData.memberBonus = userBonus.Value;


            // 获取会员资产
            UserPropertyEntity userPropertyEntity = userPropertyApp.GetMemberProperty(userId);
            if (userPropertyEntity != null && userPropertyEntity.F_Property != null)
            {
                memberDefaultData.memberProperty = userPropertyEntity.F_Property.Value;
            }
            
            return memberDefaultData;
        }
        /// <summary>
        /// 获取用户的收入总和
        /// </summary>
        /// <param name="udEntity"></param>
        /// <returns></returns>
        public decimal GetSumBounds(UserDetailEntity udEntity) {
            return memberBonusRepository.GetMemberSumAmount(udEntity.F_UserId);
        }

        /// <summary>
        /// 获取用户的当前余额
        /// </summary>
        /// <param name="udEntity"></param>
        /// <returns></returns>
        public decimal GetCurBounds(UserDetailEntity udEntity)
        {
            return memberBonusRepository.GetMemberCurAmount(udEntity.F_UserId);
        }

        /// <summary>
        /// 获取用户的当前月的收入总各
        /// </summary>
        /// <param name="udEntity"></param>
        /// <returns></returns>
        public decimal GetSumBoundsForMonth(UserDetailEntity udEntity)
        {
            return memberBonusRepository.GetMemberSumAmountForMonth(udEntity.F_UserId);
        }

        /// <summary>
        /// 获取用户的提现总额
        /// </summary>
        /// <param name="udEntity"></param>
        /// <returns></returns>
        public decimal GetSumTiXian(UserDetailEntity udEntity) {
            return userWithDrawalsRepository.GetSumTiXian(udEntity.F_UserId);
        }
        /// <summary>
        /// 执行数据清理，系统会轮询访问，每隔一小时调用一次
        /// </summary>
        public void DataClear()
        {
            //未支付订单 3小时作废
            var res = userOrderRepository.orderZF_Auto();
            logger.Debug("自动作废" + res + "条订单。");

            //已经发货订单十天后自动完成
            res = userOrderRepository.orderWC_Auto();
            logger.Debug("自动完成" + res + "条订单。");
            //注册一个月后仍是粉丝的用户从系统中删除
            res=userRepository.userDelete_auto();
            logger.Debug("自动删除" + res + "名无效用户。");
        }
    }
}